from flask import Blueprint, request
from src.service import deployment_service, git_service
from src.common import result

deployment_blueprint = Blueprint('deploy', __name__)


@deployment_blueprint.post('/action')
def deploy_branch():
    project_id = request.form.get('project_id')
    environment_id = request.form.get('environment_id')
    feature_branch_id = request.form.get('feature_branch_id')
    deployment_service.deploy_branch(project_id, environment_id, feature_branch_id)
    return result.success()


@deployment_blueprint.get('/process')
def deploy_process_status():
    environment_id = request.args.get('environment_id')
    rs = deployment_service.get_deployment_process_by_env(environment_id)
    return result.success(rs.__dict__ if rs else None)


@deployment_blueprint.get('/latest-commit')
def get_branch_latest_commit():
    branch_id = request.args.get('branch_id')
    return result.success(deployment_service.get_latest_commit(branch_id))


@deployment_blueprint.post('/branch')
def create_feature_branch():
    project_id = request.form.get('project_id')
    feature_id = request.form.get('feature_id')
    deployment_service.create_feature_branch(project_id, feature_id)
    return result.success()


@deployment_blueprint.get('/environment')
def get_env_deploy():
    environment_id = request.args.get('environment_id')
    res = deployment_service.get_environment_info(environment_id)
    return result.success({k: v.__dict__ for (k, v) in res.items()})


@deployment_blueprint.get('/deployed-branches')
def get_deployed_branches():
    environment_id = request.args.get('environment_id')
    res = deployment_service.get_deployed_branches(environment_id)
    return result.success([v.__dict__ for v in res])


@deployment_blueprint.get('/integrated-branches')
def get_integrated_branches():
    environment_id = request.args.get('environment_id')
    res = deployment_service.get_integrated_branches(environment_id)
    return result.success([v.__dict__ for v in res])


@deployment_blueprint.get('/projects')
def get_projects():
    res = deployment_service.get_projects()

    data_list = [v.__dict__ for v in res]

    return result.success_page(data_list, total=len(data_list))
